package com.ewei.web.authority.shiro;

import java.util.HashSet;
import java.util.Set;
import javax.annotation.Resource;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import com.ewei.web.authority.shiro.stateless.StatelessToken;

public class UserRealm extends AuthorizingRealm{
	@Override
	public boolean supports(AuthenticationToken token) {
		return token instanceof StatelessToken||token instanceof UsernamePasswordToken;
	}
//	@Resource
//	private UserService userService;
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		String username = (String)token.getPrincipal();
		SimpleAuthenticationInfo info = null;
		if(token instanceof UsernamePasswordToken){
			System.out.println(username);
//			User user = userService.getByUserName(username);
//			info = new SimpleAuthenticationInfo(username,user.getPassword(),getName());
			info.setCredentialsSalt(ByteSource.Util.bytes(username));//用用户名做盐
			System.out.println("using userPassordToken");
		}else{
			String tokenValue = (String) token.getCredentials();
			info = new SimpleAuthenticationInfo(username,tokenValue,getName());
			System.out.println("using StatelessToken");
		}
		return info;
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		String username = (String)principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//		Set<Role> roles = userService.findRolesByName(username);
//		Set<String> roleNames = new HashSet<String>();
//		for(Role role:roles){
//			roleNames.add(role.getName());
//		}
//		info.setRoles(roleNames);
		return info;
	}

}
